package com.block.sms.service.send;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.constant.AppRspCodeConstant;
import com.block.common.service.LogFactory;
import com.block.common.util.LocalDateUtil;
import com.block.db.entity.SmsConfigInfo;
import com.block.db.entity.SmsTemplate;
import com.block.sms.dto.SmsBalanceDTO;
import com.block.sms.dto.SmsResultDTO;
import com.block.sms.service.ISmsSendService;
import org.bouncycastle.jcajce.provider.digest.SHA1;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/*
提交地址：http://www.51miaoxin.com/sms/send
提交方法：POST
提交格式：application/x-www-form-urlencoded

账号消息属性：行业短信
连接协议：HTTP
发送账号：10046h
发送密码：hm9249yy7n
提交速度：无限制
发送速度：500/秒
接受客户IP：125.120.77.141
在线文档：http://docs.51miaoxin.com/
 */
@Service
public class MiaoXinSmsSendServiceImpl implements ISmsSendService {

    private static final Logger log = LogFactory.getCommLog();

    @Override
    public SmsResultDTO sendSms(String mobile, String outId, SmsTemplate smsTemplate, SmsConfigInfo smsConfigInfo, JSONObject paramObject) {

        SmsResultDTO resultDTO = new SmsResultDTO();
        try {
            JSONArray paramArr = paramObject.getJSONArray("paramArr");
            //accout获取的是用户ID  username  账户  账号
            String account = smsConfigInfo.getAccount();
            //content是获取的短信模板内容
            String content = StrUtil.format(smsTemplate.getTemplateContext(), paramArr.stream().toArray());

            //获取时间戳并且转为str
            String ts = LocalDateUtil.getNowDateStr(LocalDateUtil.TOTAL_DATE_TIME_SIMPLE);// “20161220202020”
            //格式化rawString
            String rawString = StrUtil.format("account={}&ts={}&secret={}", account, ts, smsConfigInfo.getSecret());
            //hutool工具封装了sha1加密可以直接调用
            String token = SecureUtil.sha1(rawString);
            //按照接口文档给的参数 先 生成 在传入
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("account", account);
            paramMap.put("token", token);
            paramMap.put("ts", ts);
            paramMap.put("mobiles", mobile);
            paramMap.put("content", content);

            HttpRequest httpRequest = HttpUtil.createPost(smsConfigInfo.getUrl());
            httpRequest.form(paramMap);

            String bodyResult = httpRequest.execute().body();
            log.info("【秒信短信服务】发送结束【requesturl】{}【paramMap】{}【bodyResult】{}",
                    smsConfigInfo.getUrl(), JSON.toJSONString(paramMap), bodyResult);

            JSONObject resultJson = JSON.parseObject(bodyResult);
            Integer code = resultJson.getInteger("code");
            String message = resultJson.getString("message");

            resultDTO.setData(bodyResult);
            resultDTO.setHttpStatus(code + "");
            resultDTO.setRequestId(outId);
            resultDTO.setMessage(message);
            if (ObjectUtil.equals(Integer.valueOf("0"), code)) {
                resultDTO.setCode(AppRspCodeConstant.SUCCESS);
                return resultDTO;
            }
        } catch (Exception exception) {
            log.error(String.format("【秒信短信服务】发送发生异常【mobile】%s【code】%s", mobile, paramObject.toJSONString()), exception);
        }
        resultDTO.setCode(AppRspCodeConstant.OPERATION_FAILURE);
        return resultDTO;
    }

    @Override
    public SmsBalanceDTO queryBalanceInfo(SmsConfigInfo smsConfigInfo) {
        return null;
    }

    public static void main(String[] args) {
        String ts = LocalDateUtil.getNowDateStr(LocalDateUtil.TOTAL_DATE_TIME_SIMPLE);
        System.out.println(ts);
        System.out.println(System.currentTimeMillis());
        System.out.println();
    }

 /*   public static String decrypt(String phonenumber, String key) throws Exception {
        //使用Cipher类获取一个实例，指定加密算法为AES/ECB/PKCS5Padding
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        //创建一个SecretKeySpec对象，将密钥转换为字节数组，并指定密钥算法为AES
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");

        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        //使用Base64解码content字符串得到加密后的字节数组，再使用Cipher对象对加密后的字节数组进行解密操作
        byte[] encryptedBytes = Base64.getDecoder().decode(phonenumber);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        //将解密后的字节数组转换为UTF-8编码的字符串并返回
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }*/


}


